//
//  MainViewController.m
//  niminban
//
//  Created by zhouteng on 16/9/30.
//  Copyright © 2016年 zhouteng. All rights reserved.
//

#import "MainViewController.h"
#import "UIViewController+MMDrawerController.h"
#import "AFNetworking.h"
#import "URLS.h"
#import "MJExtension.h"
#import "TitleView.h"
#import "ThreadViewController.h"
#import "MMDrawerBarButtonItem.h"
#import "Masonry.h"
#import "Cookie.h"
#import "COLORS.h"

#define WIDTH self.view.bounds.size.width
#define HEIGHT self.view.bounds.size.height
#define DEFAULT_FORUM_ID @"4"
#define DDEFAULT_PAGE 1

@implementation MainViewController
 static NSString *CellIdentifier = @"cell";

-(instancetype)init{
    self = [super init];
    if(self){
        lastItemReached = NO;
        isLoading =NO;
    }
    return self;
}

-(void)viewDidLoad{
    [super viewDidLoad];
   
    [self initView];
    
    [self update:DEFAULT_FORUM_ID page:DDEFAULT_PAGE];
}

-(void)initView{
    self.navigationController.navigationBar.translucent = NO;
    
    self.view.backgroundColor =GRAY_COLOR;
    
    
    UIBarButtonItem *addBtn = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:@selector(add)];
    
    MMDrawerBarButtonItem * leftDrawerButton = [[MMDrawerBarButtonItem alloc] initWithTarget:self action:@selector(leftDrawerButtonPress:)];
    [self.navigationItem setLeftBarButtonItem:leftDrawerButton animated:YES];
    
    self.navigationItem.rightBarButtonItem = addBtn;
    
    
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.backgroundColor = GRAY_COLOR;
    self.tableView.showsVerticalScrollIndicator = NO;
    self.tableView.rowHeight = UITableViewAutomaticDimension;
    self.tableView.estimatedRowHeight = 44.0;
    
    [self.tableView registerClass:[TitleView class] forCellReuseIdentifier:CellIdentifier];
    
    self.refreshControl = [[UIRefreshControl alloc] init];
    [self.refreshControl addTarget:self action:@selector(refresh) forControlEvents:UIControlEventValueChanged];
}

-(void)refresh{
    _page = 1;
    [self showF:YES];
}

-(void)leftDrawerButtonPress:(id)sender{
    [self.mm_drawerController toggleDrawerSide:MMDrawerSideLeft animated:YES completion:nil];
}

-(void)add{
    NSLog(@"add");
    [Cookie apply:^(NSString * _Nullable message) {
        
    } failure:^(NSError * _Nonnull error) {
        
    }];
}


-(void)update:(NSString *)id page:(NSInteger)page{
    _id = id;
    _page = page;
    
    [self.refreshControl beginRefreshing];
    [self.tableView setContentOffset:CGPointMake(0, -self.refreshControl.frame.size.height) animated:NO];
    [self showF:YES];
}

-(void)viewWillAppear:(BOOL)animated{
    NSLog(@"%s",__func__);
}

-(void)viewDidAppear:(BOOL)animated{
     NSLog(@"%s",__func__);
    
}


-(void)reloadData{
    [self.tableView reloadData];
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    TitleView *cell;
    cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[TitleView alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    }
    [cell setTitle:_arrTitles[indexPath.row]];
    
    if (!lastItemReached &&!isLoading && indexPath.row == [self getCount] - 1)
    {
        [self launchReload];
    }

    return cell;
}

-(void)launchReload{
    _page += 1;
    isLoading = YES;
    [self showF:NO];
}

-(NSInteger)getCount{
    if(_arrTitles){
        return _arrTitles.count;
    }else{
        return 0;
    }
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return [self getCount];
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    ThreadViewController *vc = [[ThreadViewController alloc]init];
    Title *title = _arrTitles[indexPath.row];
    [vc update:title.id page:1];
    [self.navigationController pushViewController:vc animated:YES];
}

-(void)showF:(BOOL)refresh{
    NSString *URLString = GET_F;
    NSLog(GET_F);
    AFHTTPSessionManager *magager = [AFHTTPSessionManager manager];
    
    magager.responseSerializer = [AFJSONResponseSerializer serializer];
    
    [magager GET:URLString parameters:@{@"id":_id,@"page":[NSNumber numberWithLong: _page]} progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        if(refresh){
            [self.refreshControl endRefreshing];
            _arrTitles = [Title mj_objectArrayWithKeyValuesArray:responseObject];
        }else{
            isLoading = NO;
            NSArray *titles = [Title mj_objectArrayWithKeyValuesArray:responseObject];
            if(titles.count>0){
                [_arrTitles addObjectsFromArray:titles];
            }else{
                lastItemReached = YES;
            }
            
        }
        
        NSLog(@"%@",_arrTitles);
        
        [self reloadData];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if(refresh){
            [self.refreshControl endRefreshing];
        }else{
             isLoading = NO;
        }
        NSLog(@"error");
    }];
}
@end
